package org.itsolutions.javaBackup.utils;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;

import org.itsolutions.javaBackup.exceptions.AException;
import org.itsolutions.javaBackup.exceptions.CommonException;


/**
 * 
 * @author Tomas Fecko
 */
public final class NetUtils {

	/**
	 * 
	 */
	private NetUtils() {
	}

	/**
	 * Method should find first free port from starting port number on the number of attempts.
	 * @param pStartingPort starting port, from which the available port search is starting
	 * @param pNumberOfAttempts number of attempts for finding the free port
	 * @return free port number
	 * @throws IOException exception is thrown, if no ports are free in specified range
	 */
	public static int selectPort(int pStartingPort, int pNumberOfAttempts) throws IOException {
		int port = pStartingPort;
		while (port <= pStartingPort + pNumberOfAttempts) {
			try {
				ServerSocket socket = new ServerSocket(port);
				socket.close();
				return port;
			} catch (IOException e) {
				port++;
			}
		}
		throw new IOException("Unable to find an available port...");
	}

	/**
	 * Method returns the localhost address.
	 * @return localhost as string IPV4
	 * @throws AException Thrown to indicate that the IP address of a host could not be determined. 
	 */
	public static String getLocalhostAsIPV4() throws AException {
		try {
			InetAddress localHost = Inet4Address.getLocalHost();
			return localHost.getHostAddress();
		} catch (UnknownHostException e) {
			throw new CommonException(e);
		}
	}
}



